import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, AlertController,ModalController,ViewController} from 'ionic-angular';
import { ListService } from './list.service';
import { HomePage } from '../home/home.component';
import { IndexPage } from '../index/index.component';
import { CartPage } from '../cart/cart.component';

@Component({
  selector: 'page-list',
  templateUrl: 'list.component.html',
  providers: [ListService]
})
export class ListPage implements OnInit {
  taskID: number;
  materialGroups: Array<any> = [];
  currentGroup: any;
  items: Array<any> = [];
  applies: Array<any> = [];
  indexGroups:Array<any> =[];
  changeChecked = false;
  selectedIndex:string;
  selectedCount:number = 0;

  constructor(
    public navCtrl: NavController,
    public alertCtrl: AlertController,
    public navParams: NavParams,
    public listService: ListService,
    public modalCtrl: ModalController,
    public viewCtrl:ViewController
  ) {
    this.taskID = +navParams.get('taskID');
  }

  ngOnInit() {
    //初始化栏目类别
    this.listService.listCategoryItems().subscribe(data => {
      this.materialGroups = data['materialGroups'];
      this.currentGroup = this.materialGroups[0]
      this.changeGroup(this.currentGroup);
    });
    //初始化已有列表
    // this.listService.listMaterialApplies(this.taskID).subscribe(data => data['apply'])
  }

  /**根据选择类型切换明细菜单 */
  changeGroup(group) {
    this.currentGroup = group;
    this.listService.listMaterialsByGroupID(group['groupID']).subscribe(data => {
      data['materials'].forEach(m => {
        m['materialCount'] = 0; //默认数量为0
        m['indexGroups'].forEach(grp => {
          grp['defaultVal'] = grp['indexs'][0]['idxValue'];//默认选中第一个属性指标
        });
        this.applies.forEach(element => {
          if(element.materialID == m.materialID){
            m['materialCount'] = element['materialCount'];
            m['materialIndexs'] = element['materialIndexs'];
          }
        });
      })
      this.items = data['materials'];
    });
  }

  /**数量减少 */
  decrease(item) {
    if (item.materialCount > 0) {
      this.changeChecked = true;
      item.materialCount--;
      this.selectedCount--;
      this.applies.forEach((e, idx) => {
        //物品相同并且属性相同
        if (e['materialID'] == item['materialID']) {
          e.materialCount--;
          if (e.materialCount == 0) {
            this.applies.splice(idx, 1);
          }
        }
      });
    }
  }

  /**数量增加 */
  increase(item) {
    this.selectedCount++;
    if (item.materialCount <= 99) {
      this.changeChecked = true;
      if (item.materialCount == 0) {
        this.applies.push({
          'taskID': this.taskID,
          'materialID': item['materialID'],
          'materialName': item['materialName'],
          'materialPicture': item['materialPicture'],
          'groupID': item['groupID'],
          'groupName': this.currentGroup['groupName'],
          'materialCount': 1,
          'materialPrice': item['materialPrice'],
          'materialIndexs': item['materialIndexs']
        });
      } else {
        //找到申请表中已有的记录，数量加1
        this.applies.forEach(e => {
          if (e['materialID'] == item['materialID']) {
            e['materialCount']++;
          }
        });
      }
      item.materialCount++;
    }
  }

  /**显示选中的详情 */
  showCheckedDetail() {
    console.log(this.applies);
    let profileModal = this.modalCtrl.create(CartPage, { applies: this.applies,selectedCount:this.selectedCount});
    profileModal.onDidDismiss(data => {
      if(data.applies != null){
        this.applies = data.applies;
        this.selectedCount = 0;
        this.items.forEach(ele => {
          this.applies.forEach(e =>{
            if(e.materialID == ele.materialID){
              ele['materialCount'] = e['materialCount'];
              this.selectedCount += e['materialCount'];
            }
          });
        });
      }else{
        this.navCtrl.setRoot(HomePage);
      }
    });
    
    profileModal.present();
  }


  /** 指标选取 */
  openIndex(item) {
      let profileModal = this.modalCtrl.create(IndexPage, { materialID: item['materialID'],materialIndexs: item['materialIndexs'],materialIndexIds:item['materialIndexIds']});
      profileModal.onDidDismiss(data => {
        console.log("select index return",data);
        if(data != null){
          item['materialIndexs'] = data.materialIndexs;
          item['materialIndexIds'] = data.materialIndexIds;
          if(this.applies != null){
            //找到申请表中已有的记录，数量加1
            this.applies.forEach(e => {
              if (e['materialID'] == item['materialID']) {
                e['materialIndexs'] = data.materialIndexs;
                e['materialIndexIds'] = data.materialIndexIds;
              }
            });
          }
        }
      });
      
      profileModal.present();
  }

  /**提交上报 */
  submit() {
    if (this.applies.length > 0) {
      let priceCount = 0, materialCount = 0;
      this.applies.forEach(item => {
        materialCount += item['materialCount'];
        priceCount += (item['materialCount'] * item['materialPrice']);
      });

      this.alertCtrl.create({
        message: '共选择'+materialCount+'件物品，总价￥'+priceCount+'元，您确定要提交申请吗？',
        buttons: [
          {
            text: '取消',
            handler: () => { }
          },
          {
            text: '确定',
            handler: () => {
              //提交保存
              this.listService.submitApplay(this.applies).subscribe(data => {
                //关闭当前页
                this.viewCtrl.dismiss({});
              });
            }
          }

        ]
      }).present();
    }
  }
}